// pages/postArticle/postArticle.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    session_key:'',
    imgs: [],
    upload_picture_list: [],
    imgpath_arr: [],
    countNum: 3,
    albumIndex: -1,
    albums: [],
    textarea:'',
    imgPathstr:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      session_key: wx.getStorageSync("token")
    })
  },
  //获取用户输入的内容
  textareaFocus: function (e) {
    this.setData({
      textarea: e.detail.value
    })
  },
  /**
    * 上传图片
    */
  chooseImage: function () {
    var that = this;
    var items = that.data.upload_picture_list;
    if (items.length >= that.data.countNum) {
      wx.showToast({
        title: '最多选择' + that.data.countNum + '张！',
      })
      return;
    }
    wx.chooseImage({
      count: 3, // 默认3
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        
        that.data.imgs = that.data.imgs.concat(res.tempFilePaths)
        that.data.imgpath_arr = that.data.imgpath_arr.concat(res.tempFilePaths)
        for (let i in res.tempFiles) {
          res.tempFiles[i]['path_server'] = '';
          items.push(res.tempFiles[i])
        }
        that.setData({
          upload_picture_list: items
        });

        //上传图片
        var uploadImg_list = that.data.upload_picture_list;
        var img_patharr = that.data.imgpath_arr;
        if (uploadImg_list.length != 0 && img_patharr.length != 0) {
          that.uploadimgs({
            url: app.globalData.httpsPath + '/upload',//这里是你图片上传的接口
            filePath: uploadImg_list,//这里是选取的图片的地址数组
            imgpath: img_patharr
          });
        }

      }
    })
  },
  //预览图片
  previewImage: function (e) {
    var _that = this;
    wx.previewImage({
      current: _that.data.imgs[e.currentTarget.dataset.index],
      urls: _that.data.imgs
    })
  },
  //删除 图片
  delClick:function(e){
    var _that = this;
    _that.data.upload_picture_list.splice(e.currentTarget.dataset.index, 1);
    _that.data.imgs.splice(e.currentTarget.dataset.index, 1);
    _that.setData({
      upload_picture_list: _that.data.upload_picture_list
    });
  },
  //发布动态
  releaseArticle:function(){
    var that = this;
    if (that.data.textarea ==""){
      wx.showToast({
        icon: "none",
        title: '请输入内容！'
      })
      return false;
    }
    var _textarea = that.data.textarea.split('\n').join('&hc')
    wx.request({
      url: app.globalData.httpsPath + '/article/save',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: that.data.session_key,
        contents: _textarea,
        pics: that.data.imgPathstr
      },
      //请求后台数据成功  
      success: function (res) {
        var _info = res.data.data;
        // console.info(res.data.msg)
        wx.showModal({
          title: '提示',
          content: res.data.msg,
          showCancel: false
        })
        setTimeout(function () {
          wx.reLaunch({
            url: '../personalCenter/personalCenter'
          })
        }, 1000)
      }
    });
    
   
    
  },
  //上传图片到服务器
  uploadimgs: function (data) {
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;

    wx.uploadFile({
      url: data.url,
      filePath:data.filePath[i].path,
      name: 'pic',
      formData: {
        'token': that.data.session_key
      },
      success: (resp) => {
        success++;
        var _imgdata = JSON.parse(resp.data);
        if (_imgdata.status == true){
          data.filePath[i]['path_server'] = _imgdata.data;
          data.imgpath[i] = _imgdata.data
        }
      },
      fail: (res) => {
        fail++;//图片上传失败，图片上传失败的变量+1
      },
      complete: () => {
        i++;
        if (i == data.filePath.length) { //当图片传完时，停止调用  
          var strimg = data.imgpath.join(",");
          that.setData({
            imgpath_arr: data.imgpath,
            imgPathstr: strimg
          })
          // console.log('执行完毕');
          // console.log('成功：' + success + " 失败：" + fail);
        } else {//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgs(data);
        }

      }
    });
  },

})